from .base_monitor import BaseMonitor
import json
import subprocess
import requests
from tjob.initialize.setup_envs import DLC
from datetime import datetime


class PaiMonitor(BaseMonitor):
    def single_monitor(self, id):
        # check job status
        mon_cmd = f"{DLC} get job {id}"
        mon_cmd = mon_cmd.split(" ")
        result = subprocess.run(mon_cmd, capture_output=True)
        status = None
        job_name = None
        created_at = None
        finished_at = None
        try:
            resp_info = json.loads(result.stdout)
            status = resp_info["Status"]
            job_name = resp_info["DisplayName"]
            created_at = resp_info["GmtRunningTime"]
            finished_at = resp_info["GmtFinishTime"]
        except Exception:
            pass
        return status, job_name, created_at, finished_at

    def send_msg(self, jobname, joburl, user_lst, status, created_at, finished_at):
        """send msg to feishu

        Args:
            jobname (str): display name in pai
            joburl (str): job url
            user_lst (list): OA email, like: ["xxxxxxx@deeproute.ai"].
            job_status (str): job status.
        """

        # token generate from cloud team
        token_str = (
            "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7Im5hbWUiOiJwYWlfcGxhdGZvcm0iLCJlbWFpbCI6ImRlY2h1YW"  # noqa
            + "5neW91QGRlZXByb3V0ZS5haSIsImVuX25hbWUiOiJ0ZW5hbnRfYTE3NTQ5Mzg0YTk2ZTFmNjM0ZWViYjNmZWYzY2M4NDgiLCJhc"  # noqa
            + "HBfaW5mbyI6e30sImV4cGlyZSI6LTEsImRlc2NyaWJlIjoicGFpIFx1NWU3M1x1NTNmMFx1NzY4NFx1NGY3Zlx1NzUyOFx1OTAx"  # noqa
            + "YVx1NzdlNSIsImNyZWF0ZV90aW1lIjoiMjAyNC0wMS0xNSAwMjoyNzo1OS4xMzE2MDgifSwic3ViIjoiYWNjZXNzIn0.fUJFtya"  # noqa
            + "CKXu8Pmz6zS6u2aM23LRQdo9Z_QXW4H-vitU"
        )
        secret = "e8a4311b85bcb91803639ce067ddcc2c606a62f58c12f441e01e328dc454b2e5"
        url = "https://alarm-system.deeproute.cn/api/feishu/send_message"

        create_time = datetime.now().strftime("%Y_%m_%d")
        headers = {
            "accept": "application/json",
            "x-secret": secret,
            "token": token_str,
            "Content-Type": "application/json",
        }

        json_data = {
            "notifier": "feishu",
            "to_notified_users": user_lst,
            "content": {
                "platform": "PAI",
                "project_name": "PAI-Usage",
                "project_key": "PAI-Usage",
                "alarm_type": "info",
                "title": "PAI-Usage",
                "content": "string",
                "extensions": {
                    "color": "blue",
                    "title": f"Your job: {jobname}, status is: {status}",
                    "time": create_time,
                    "url": joburl,
                    "start": created_at,
                    "end": finished_at,
                },
            },
            "template": {
                "root_path": "development/dechuangyou/templates",
                "filename": "pai_job_v2.jinja2",
                "is_s3": True,
            },
        }
        requests.post(url, headers=headers, json=json_data)
